package com.yeskery.nut.web.demo.biz;

import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.annotation.bean.LazyInject;
import com.yeskery.nut.core.RequestApplicationContext;
import com.yeskery.nut.extend.oauth.AuthorizationCodeGenerator;
import com.yeskery.nut.extend.oauth.OAuth2ServerPlugin;
import com.yeskery.nut.util.DigestUtils;
import com.yeskery.nut.web.demo.domain.User;
import com.yeskery.nut.web.demo.service.UserService;

/**
 * OAuth biz
 * @author YESKERY
 * 2024/11/4
 */
@Component
public class OAuthBiz {

    @LazyInject
    @Autowired
    private UserService userService;

    @LazyInject
    @Autowired
    private AuthorizationCodeGenerator authorizationCodeGenerator;

    /**
     * 获取用户ID
     * @return 用户ID
     */
    public String getCurrentOAuthUserName() {
        return (String) RequestApplicationContext.getResource(OAuth2ServerPlugin.AUTHORIZE_REQUEST_CODE_VALUE_KEY);
    }

    /**
     * 验证用户
     * @param username 用户名
     */
    public boolean validUser(String username, String password) {
        return userService.lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getPassword, DigestUtils.md5DigestAsHex(password))
                .count() > 0;
    }

    /**
     * 获取授权码
     * @param username 用户名
     * @return 授权码
     */
    public String getAuthorizationCode(String username) {
        return authorizationCodeGenerator.generateAuthorizationCode(username);
    }
}
